package com.zhitan.ems.app.iot.controller;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.influxdb.query.FluxTable;
import com.zhitan.ems.app.iot.entity.DeviceTopologyPointEntity;
import com.zhitan.ems.app.iot.service.DeviceTopologyPointService;
import com.zhitan.ems.app.iot.vo.DeviceTopologyPointVO;
import com.zhitan.ems.app.iot.vo.TopologyPointDataVO;
import com.zhitan.ems.app.iot.wrapper.DeviceTopologyPointWrapper;
import com.zhitan.ems.app.sse.SseTopologyServiceImpl;
import com.zhitan.ems.app.stat.service.impl.InfluxdbService;
import com.zhitan.ems.app.stat.vo.DeviceDataDateVo;
import com.zhitan.ems.common.annotation.Log;
import com.zhitan.ems.common.core.controller.BaseController;
import com.zhitan.ems.common.core.domain.R;
import com.zhitan.ems.common.enums.BusinessType;
import com.zhitan.ems.common.utils.DateUtils;
import com.zhitan.ems.common.utils.StringUtils;
import com.zhitan.ems.framework.core.vo.VPage;
import com.zhitan.ems.framework.core.vo.VQueryKit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
 * 设备组态图点位
 * @author zhitan
 * @email 
 * @date 2025-10-28 23:01:38
 */
@Api(tags = "设备组态图点位", value = "设备组态图点位")
@RestController
@RequestMapping("intra/iot/devicetopologypoint")
public class DeviceTopologyPointController extends BaseController{
    @Autowired
    private DeviceTopologyPointService deviceTopologyPointService;
    @Autowired
    private InfluxdbService influxdbService;
    @Value("${influx.bucket}")
    private String bucket;
    @Resource
	private SseTopologyServiceImpl sseTopologyService;
    /**
     * 列表
     */
    @ApiOperation(value = "列表", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
		})
    @GetMapping("/browse")
    @PreAuthorize("@ss.hasPermi('iot:devicetopologypoint:list')")
    public R<VPage<DeviceTopologyPointVO>> browse(@RequestParam Map<String, Object> params){
        QueryWrapper<DeviceTopologyPointEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), DeviceTopologyPointEntity.class);
        queryWrapper.orderByDesc("id");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        IPage<DeviceTopologyPointEntity> pages = deviceTopologyPointService.page(VQueryKit.getPage(params), queryWrapper);
        return R.data(DeviceTopologyPointWrapper.build().toVPageVO(pages));
    }
    
    @ApiOperation(value = "获取组态图列表", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
		})
    @GetMapping("/browseByTopologyId")
    @PreAuthorize("@ss.hasPermi('iot:devicetopologypoint:list')")
    public R<List<DeviceTopologyPointVO>> browseByTopologyId(@PathVariable("topologyId") Long topologyId){
        QueryWrapper<DeviceTopologyPointEntity> queryWrapper=new QueryWrapper<DeviceTopologyPointEntity>();
        queryWrapper.select(
				"id", 
				"topology_id as topologyId", 
				"status", 
				"t_name as tName", 
				"t_topic as tTopic", 
				"t_width as tWidth", 
				"t_height as tHeight", 
				"t_background_color as tBackgroundColor", 
				"update_at"
			);
        queryWrapper.eq("topology_id", topologyId);
         List<DeviceTopologyPointEntity> list = deviceTopologyPointService.list(queryWrapper);
        return R.data(DeviceTopologyPointWrapper.build().listVO(list));
    }
    
    @GetMapping("/listStat")
    @PreAuthorize("@ss.hasPermi('iot:devicetopologypoint:list')")
    public R<Map<String, Object>> listStat(@RequestParam Map<String, Object> params)throws ParseException{
         QueryWrapper<DeviceTopologyPointEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), DeviceTopologyPointEntity.class);
         queryWrapper.select("count(id) as total,sum(id) as all");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        if(params.containsKey("createDate")) {
            queryWrapper.between("create_at",
                    DateUtils.getStartOfDate(DateUtils.str_ToDate(params.get("createDate").toString())),
                    DateUtils.getEndOfDate(DateUtils.str_ToDate(params.get("createDate").toString()))
              );   
        }
        Map<String, Object>  stat=deviceTopologyPointService.getMap(queryWrapper);
        return R.data(stat);
    }
   
    /**
     * 信息
     */
    @ApiOperation(value = "获取单个组态图详情", response = DeviceTopologyPointVO.class)
    @GetMapping("/detail/{id}")
    @PreAuthorize("@ss.hasPermi('iot:devicetopologypoint:info')")
    public R<DeviceTopologyPointVO> detail(@PathVariable("id") Long id){
		DeviceTopologyPointEntity deviceTopologyPoint = deviceTopologyPointService.getById(id);
	    return R.data(DeviceTopologyPointWrapper.build().entityVO(deviceTopologyPoint));
    }
    
    @ApiOperation(value = "获取点位初始化数据", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "nodeKeyList", value = "标题",  paramType = "query", required = false, dataType =  "List"),
		})
    @PostMapping("/browsePointData")
    @PreAuthorize("@ss.hasPermi('iot:devicetopologypoint:list')")
    public R<List<TopologyPointDataVO>> browsePointData(@RequestBody List<String> nodeKeyList){
        List<TopologyPointDataVO> listData=new ArrayList<TopologyPointDataVO>();
        for(String nodeKey:nodeKeyList) {
             String table ="emsplus";
     		 String start ="-1d";
     		 String iotNodeKey=nodeKey;
     		 if(nodeKey.contains("@")) {
     			iotNodeKey=nodeKey.replace("@", "_");
     		 }
     		 try {
     			 List<FluxTable> fluxTableList = influxdbService.getLastInfluxDataByDeviceCodePoint(bucket, start, null, table, iotNodeKey);
             	 DeviceDataDateVo dataDateVo = InfluxdbService.getResultOneRowByTagProcess(fluxTableList,true); 
             	 if(dataDateVo==null||dataDateVo.getValue()==null) {
             		TopologyPointDataVO itemData=new TopologyPointDataVO();
                	itemData.setNodeKey(nodeKey);
                	itemData.setNodeValue("-1");
                	listData.add(itemData);
                	sseTopologyService.setTopologMap(nodeKey,itemData);
             	 }else {
             		TopologyPointDataVO itemData=new TopologyPointDataVO();
                	itemData.setNodeKey(nodeKey);
                	itemData.setNodeValue(dataDateVo.getValue().toString());
                	listData.add(itemData);
                	sseTopologyService.setTopologMap(nodeKey,itemData);
             	 }
			} catch (Exception e) {
			}
        }
        return R.data(listData);
    }
    
     /**
     * 保存&更新 
     */
    @Log(title = "设备组态图点位", businessType = BusinessType.ADDANDEDIT)
    @ApiOperation(value = "保存&更新", response = Boolean.class)
    @PostMapping("/submit")
    @PreAuthorize("@ss.hasPermi('iot:devicetopologypoint:save')")
    public R<DeviceTopologyPointVO> submit(@Valid @RequestBody DeviceTopologyPointVO deviceTopologyPoint){
    	 if(deviceTopologyPoint.getId()==null) {
           return add(deviceTopologyPoint);
         }else {
           return edit(deviceTopologyPoint);
        }
    }
    
    @Log(title = "设备组态图点位", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增", response = Boolean.class)
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('iot:devicetopologypoint:save')")
    public R<DeviceTopologyPointVO> add(@Valid @RequestBody DeviceTopologyPointVO deviceTopologyPoint){
   		if(deviceTopologyPoint.getId()==null) {
            deviceTopologyPoint.setCreateAt(new Date());
            deviceTopologyPoint.setIsDelete(0);
            deviceTopologyPoint.setUpdateAt(new Date());
        } 
    	if(deviceTopologyPointService.save(deviceTopologyPoint)) {
    		 return R.ok(deviceTopologyPoint);
    	 }
    	return R.error("数据错误");
    }
    
    @Log(title = "设备组态图点位", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "更新", response = Boolean.class)
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPermi('iot:devicetopologypoint:update')")
    public R<DeviceTopologyPointVO> edit(@Valid @RequestBody DeviceTopologyPointVO deviceTopologyPoint){
   		deviceTopologyPoint.setUpdateAt(new Date());
    	if(deviceTopologyPointService.updateById(deviceTopologyPoint)) {
    		 return R.ok(deviceTopologyPoint);
    	 }
    	return R.error("数据错误");
    }
    /**
     * 删除
     */
    @ApiOperation(value = "删除", response = Boolean.class)
    @DeleteMapping("/delete")
    @PreAuthorize("@ss.hasPermi('iot:devicetopologypoint:delete')")
    @Log(title = "设备组态图点位", businessType = BusinessType.DELETE)
    public R<Boolean> delete(@RequestBody Long[] ids){
        return R.ok(deviceTopologyPointService.removeByIds(Arrays.asList(ids)));
    }

}
